import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores/user'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/login',
      name: 'login',
      component: () => import('@/views/LoginView.vue'),
      meta: { requiresAuth: false }
    },
    // OAuth2客户端应用路由
    {
      path: '/oauth',
      name: 'oauth',
      component: () => import('@/views/OAuthLayout.vue'),
      meta: { requiresAuth: false },
      children: [
        {
          path: '',
          name: 'oauth-home',
          component: () => import('@/views/Home.vue')
        },
        {
          path: 'callback',
          name: 'oauth-callback',
          component: () => import('@/views/OAuthCallback.vue')
        }
      ]
    },
    {
      path: '/',
      name: 'layout',
      component: () => import('@/views/LayoutView.vue'),
      meta: { requiresAuth: true },
      children: [
        {
          path: '',
          name: 'home',
          component: () => import('@/views/HomeView.vue'),
          meta: { title: '首页' }
        },
        {
          path: 'profile',
          name: 'profile',
          component: () => import('@/views/ProfileView.vue'),
          meta: { title: '个人资料' }
        },
        {
          path: 'users',
          name: 'users',
          component: () => import('@/views/UserListView.vue'),
          meta: { title: '用户列表', roles: ['ADMIN', 'MANAGER'] }
        }
      ]
    },
    {
      path: '/:pathMatch(.*)*',
      name: 'not-found',
      component: () => import('@/views/NotFoundView.vue')
    }
  ]
})

// 全局前置守卫
router.beforeEach(async (to, from, next) => {
  // 如果是OAuth相关路由，直接通过
  if (to.path.startsWith('/oauth')) {
    next()
    return
  }
  
  const userStore = useUserStore()
  const requiresAuth = to.matched.some(record => record.meta.requiresAuth)
  
  // 如果用户已登录但没有用户信息，获取用户信息
  if (userStore.isAuthenticated && !userStore.userInfo) {
    try {
      await userStore.fetchUserInfo()
    } catch (error) {
      userStore.resetState()
      next({ name: 'login', query: { redirect: to.fullPath } })
      return
    }
  }
  
  // 检查页面是否需要认证
  if (requiresAuth && !userStore.isAuthenticated) {
    // 未登录，重定向到登录页
    next({ name: 'login', query: { redirect: to.fullPath } })
  } 
  // 检查角色权限
  else if (to.meta.roles && !userStore.hasAnyRole(to.meta.roles as string[])) {
    // 无权限访问，返回首页
    next({ name: 'home' })
  } 
  // 如果已登录且访问登录页，重定向到首页
  else if (to.name === 'login' && userStore.isAuthenticated) {
    next({ name: 'home' })
  } 
  // 其他情况正常通过
  else {
    next()
  }
})

export default router 